<template>
	<div class="container_right">
		<el-card v-if="flag !== '1'" shadow="never">
			<div class="chunk">
				<div class="title">审批意见</div>
				<div class="content">
					<el-input
						:autosize="{
							minRows: 3,
							maxRows: 3,
						}"
						type="textarea"
						clearable
						:placeholder="'请输入内容'"
						v-model="suggest.message"
						resize="none"
						show-word-limit></el-input>
				</div>
				<div class="handleBox">
					<el-dropdown trigger="click" v-show="apply_sett.length > 0">
						<el-button type="">
							更多操作
							<i class="el-icon-arrow-down el-icon--right"></i>
						</el-button>

						<el-dropdown-menu slot="dropdown">
							<el-dropdown-item v-for="item in apply_sett">
								<span
									@click="handle_audit(item.value)"
									class="dropdown_item"
									:style="{
										width: '67px',
										display: 'block',
										textAlign: 'center',
										lineHeight: '36px',
									}">
									{{ item.label }}
								</span>
							</el-dropdown-item>
						</el-dropdown-menu>
					</el-dropdown>
					<el-button
						type="primary"
						@click="handle_audit('3')"
						v-if="show_btnGroup('3')"
						plain>
						驳回
					</el-button>
					<el-button type="primary" @click="handle_audit('7')">
						通过
					</el-button>
				</div>
			</div>
		</el-card>
		<el-card v-if="flag !== '1'" shadow="never">
			<div class="chunk">
				<div class="title">备忘录</div>
				<div class="content">
					<el-input
						ref="textarea"
						:autosize="{
							minRows: 3,
							maxRows: 3,
						}"
						type="textarea"
						clearable
						:placeholder="'请输入内容'"
						v-model="remarkCopy"
						resize="none"
						show-word-limit></el-input>
				</div>
				<div class="handleBox">
					<el-button type="primary" @click="save_moment">
						暂存
					</el-button>
				</div>
			</div>
		</el-card>
		<el-card shadow="never" v-if="userAuthority">
			<div class="chunk">
				<div class="title">审批流程</div>
				<div class="content">
					<el-timeline :reverse="true">
						<el-timeline-item
							v-for="(activity, index) in activities"
							:key="index"
							:color="
								activity.auditResults == '拒绝'
									? '#F5222D'
									: activity.nodeType == 3 ||
									  activity.nodeType == 4
									? '#DADADA'
									: activity.nodeType == 1
									? '#1890FF'
									: activity.nodeType == 2
									? '#1890FF'
									: ''
							">
							<div class="status">
								<span
									class="name"
									v-if="
										activity.nodeType !== 3 &&
										activity.nodeType !== 4
									">
									{{ activity.assignee }}
								</span>
								<span class="comp">
									{{ activity.activityName }}
								</span>
								<span class="time">
									{{ activity.endTime }}
								</span>
							</div>
							<div
								v-if="activity.nodeType == 3"
								class="timeLineItem willAudit">
								<div class="unpass">
									待{{ activity.assigneeName }}审核
								</div>
								<div v-if="activity.message">
									原因：
									<span>{{ activity.message }}</span>
								</div>
							</div>
							<div
								v-else-if="activity.nodeType == 4"
								class="timeLineItem willAudit">
								<div class="unpass">待审核</div>
								<div v-if="activity.message">
									原因：
									<span>{{ activity.message }}</span>
								</div>
							</div>
							<div v-else>
								<div
									v-if="activity.auditResults == '拒绝'"
									class="timeLineItem willAudit">
									<div class="unpass">拒绝</div>
									<div>
										原因：
										<span>{{ activity.message }}</span>
									</div>
								</div>
								<div v-else class="timeLineItem">
									<div class="pass">
										{{ activity.auditResults }}
									</div>
									<div
										class="willAudit"
										v-if="activity.message">
										原因：
										<span>{{ activity.message }}</span>
									</div>
								</div>
							</div>
							<!-- <div -->
							<!-- v-if=" -->
							<!-- activity.nodeType == 1 || activity.nodeType == 2 -->
							<!-- " -->
							<!-- > -->
							<!-- <div> -->
							<!-- <span v-if="activity.nodeType == 2"> -->
							<!-- {{ activity.activityName }} -->
							<!-- </span> -->
							<!-- {{ activity.assignee }} -->
							<!-- {{ activity.auditResults }} -->
							<!-- </div> -->
							<!-- <div v-if="activity.message"> -->
							<!-- 原因： {{ activity.message }} -->
							<!-- </div> -->
							<!-- <div class="timeLine_time" v-if="activity.endTime"> -->
							<!-- {{ activity.endTime }} -->
							<!-- </div> -->
							<!-- </div> -->
							<!-- <div -->
							<!-- v-if=" -->
							<!-- activity.nodeType == 3 || activity.nodeType == 4 -->
							<!-- " -->
							<!-- > -->
							<!-- 待{{ activity.activityName }}审核 -->
							<!-- </div> -->
						</el-timeline-item>
					</el-timeline>
				</div>
			</div>
		</el-card>

		<el-dialog
			:title="dialog.title"
			:visible.sync="dialog.show"
			append-to-body
			@closed="dialog_closed">
			<div class="dialog_content">
				<el-form
					:model="dialog.params"
					ref="dialogForm"
					label-width="80px"
					:inline="false"
					size="normal">
					<el-form-item
						label="驳回节点"
						v-if="dialog.flag == '3'"
						prop="targetKey"
						:rules="[
							{
								required: true,
								message: '请选择驳回节点',
								trigger: 'change',
							},
						]">
						<el-select
							v-loading="dialog.selectLoading"
							v-model="dialog.params.targetKey"
							placeholder="请选择"
							size="mini"
							filterable>
							<el-option
								v-for="item in targetKeyList"
								:key="item.id"
								:label="item.name"
								:value="item.id"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item
						label="转交人"
						v-if="dialog.flag == '1'"
						prop="handoverId"
						:rules="[
							{
								required: true,
								message: '请选择转交人',
								trigger: 'change',
							},
						]">
						<el-select
							v-loading="dialog.selectLoading"
							v-model="dialog.params.handoverId"
							placeholder="请选择"
							size="mini"
							filterable>
							<el-option
								v-for="item in handoverIdList"
								:key="item.id"
								:label="item.name"
								:value="item.id"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item
						label="加签人"
						v-if="dialog.flag == '2'"
						prop="reviewerId"
						:rules="[
							{
								required: true,
								message: '请选择加签人',
								trigger: 'change',
							},
						]">
						<el-select
							v-loading="dialog.selectLoading"
							v-model="dialog.params.reviewerId"
							placeholder="请选择"
							size="mini"
							filterable>
							<el-option
								v-for="item in handoverIdList"
								:key="item.id"
								:label="item.name"
								:value="item.id"></el-option>
						</el-select>
					</el-form-item>
				</el-form>
			</div>
			<span slot="footer">
				<el-button @click="dialog.show = false">取消</el-button>
				<el-button type="primary" @click="handleDialog_sure">
					确认
				</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import Cookies from 'js-cookie';
	import * as apis from '@/api/flowable/examine/details/api.js';
	import { getCCUser } from '@/api/flowable/model';
	export default {
		dicts: ['apply_sett'],
		props: {
			infoData: {
				default: {},
			},
			stageRemark: {
				required: true,
			},
			formData: {
				default: {},
			},
			processId: {
				required: true,
			},
			flag: {
				required: true,
			},
			remark: {
				default: '',
			},
			taskId: {
				required: true,
			},

			curreentActive: {
				default: {},
			},
			components: {
				default: () => {
					return [];
				},
			},
			activities: {
				required: true,
			},
			isSuspended: {
				required: true,
			},
			userAuthority: {
				required: true,
			},
		},
		computed: {
			userId() {
				return Cookies.get('userId');
			},
			apply_sett() {
				let btns = this.dicts.apply_sett.filter(item => {
					return this.curreentActive?.activityConfig?.auditConfig?.includes(
						item.value,
					);
				});
				return btns;
			},
			targetKeyList() {
				if (
					this.dicts.ReturnList.length == 1 &&
					this.dicts.ReturnList[0].id == 'start_event'
				) {
					return this.dicts.ReturnList;
				} else {
					let list = this.dicts.ReturnList.filter(item => {
						return this.curreentActive?.activityConfig?.rejectActivity?.includes(
							item.id,
						);
					});
					return list;
				}
			},
			// handoverIdList() {
			//     return [
			//         {
			//             id: 1,
			//             name: 1,
			//         },
			//     ];
			// },
			reviewerIdList() {
				return [];
			},
			remarkCopy: {
				get() {
					return this.remark;
				},
				set(val) {
					this.$emit('setRemark', val);
				},
			},
		},
		watch: {
			stageRemark: {
				handler(val) {
					this.remarkCopy = this.stageRemark;
					console.log(val);
				},
			},
		},
		data() {
			return {
				suggest: {},
				// activities: [],
				dicts: {
					apply_sett: [
						{
							label: '转办',
							value: '1',
						},
						{
							label: '加签',
							value: '2',
						},
						{
							label: '待定',
							value: '4',
						},
						{
							label: '拒绝',
							value: '5',
						},
						{
							label: '建议拒绝',
							value: '6',
						},
						// {
						//     label: "抄送",
						//     value: "8",
						// },
					],
					ReturnList: [],
				},
				dialog: {
					title: '',
					show: false,
					flag: '',
					loading: false,
					selectLoading: false,
					params: {
						targetKey: '',
					},
					dicts: {
						targetKeyList: [],
					},
				},
				handoverIdList: [], // 转交人
			};
		},
		created() {
			// this.getFlowRecord();
		},
		mounted() {},
		methods: {
			// 获取调单用户人员
			getCcUsers() {
				getCCUser().then(res => {
					this.handoverIdList = [];
					res.data.map(item => {
						let obj = {
							name: item.nickName,
							id: item.userId?.toString(),
						};

						this.handoverIdList.push(obj);
					});
				});
			},
			getReturnList() {
				return new Promise(resolve => {
					this.dialog.selectLoading = true;
					let params = {
						taskId: this.taskId,
					};
					apis?.ReturnList(params)
						.then(res => {
							if (res.code == 200) {
								this.dicts.ReturnList = res.data;
							}
						})
						.finally(() => {
							this.dialog.selectLoading = false;
							resolve();
						});
				});
			},
			show_btnGroup(value) {
				return this.curreentActive?.activityConfig?.auditConfig?.includes(
					value,
				);
			},
			getFlowRecord() {
				let params = {
					id: this.processId,
				};
				apis?.FlowRecord?.(params).then(res => {
					this.activities = res?.data ?? [];
				});
			},
			async handle_audit(val) {
				await this.submit();
				// 1:转交 2:加签 3:驳回 4:待定 5:拒绝 6:建议拒绝 7:审核通过 8:加签审核
				this.dialog.flag = val;
				switch (val) {
					case '7':
						this.handle_pass(val);
						break;
					case '3':
						this.dialog.title = '驳回';
						this.getReturnList();
						this.openDialog(val);
						break;
					case '2':
						this.dialog.title = '加签';
						this.getCcUsers();
						this.openDialog(val);
						break;
					case '4':
						this.$confirm('确定更改为待定状态？', '提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'warning',
						}).then(() => {
							this.handle_pass(val);
						});
						break;
					case '1':
						this.dialog.title = '转交';
						this.getCcUsers();
						this.openDialog(val);
						break;
					case '5':
						this.$confirm('确定更改为拒绝状态？', '提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'warning',
						}).then(() => {
							this.handle_pass(val);
						});
						break;
					case '6':
						this.$confirm('确定更改为建议拒绝状态？', '提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'warning',
						}).then(() => {
							this.handle_pass(val);
						});
						break;
					case '8':
						this.$confirm('确定更改为加签审核状态？', '提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'warning',
						}).then(() => {
							this.handle_pass(val);
						});
						break;
					default:
						break;
				}
			},
			openDialog() {
				this.dialog.show = true;
			},
			async handle_pass(val) {
				let result = true;
				for (let index = 0; index < this.components.length; index++) {
					const element = this.components[index];
					let pass;
					if (element?.valid) {
						pass = await element?.valid?.();
					} else {
						pass = true;
					}
					result = result && pass;
				}
				if (val !== '5') {
					if (!result) {
						this.$message({
							type: 'warn',
							message: '请先完善信息',
						});
						this.scrollToError();
						return;
					}
				}

				await this.submit();
				const loading = this.$loading({
					lock: true,
					text: 'loading...',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)',
				});
				let infoData = JSON.stringify(this.infoData);
				let customFormData = JSON.stringify(this.formData);
				let word = '';
				let item = this.dicts.apply_sett.find(
					item => item.value == val,
				);
				if (item) {
					word = item.label;
				}
				if (val == '7') {
					word = '审核';
				}
				let params = {
					flag: val,
					message: this.suggest?.message ?? '',
					processInstanceId: this.processId,
					groupId: '1',
					userId: this.userId,
					formData: infoData,
					customFormData: customFormData,
				};
				apis?.FlowAudit(params)
					.then(res => {
						if (res.code == 200) {
							loading.close();
							this.$message.success(`${word}成功`);
							const obj = this.$route;
							this.$tab.closeOpenPage(obj);
							this.$router.push({
								name: 'Approve',
								// path: "/workflow/examine/flowable/examine/list",
							});
						}
					})
					.catch(err => {
						loading.close();
					});
			},
			async save_moment() {
				await this.submit();
				let params = {
					state: '3',
					id: this.processId,
					taskId: this.taskId,
					remark: this.remarkCopy ?? '',
				};
				const loading = this.$loading({
					lock: true,
					text: 'loading...',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)',
				});
				// console.log(params);
				// return;
				apis?.UpdateState(params)
					.then(res => {
						if (res.code == 200) {
							loading.close();
							this.$message.success('暂存成功');
							const obj = this.$route;
							this.$tab.closeOpenPage(obj);
							this.$router.push({
								name: 'Approve',
								// path: "/workflow/examine/flowable/examine/list",
							});
						}
					})
					.catch(e => {
						loading.close();
					});
			},
			async submit() {
				for (let index = 0; index < this.components.length; index++) {
					const element = this.components[index];
					console.log(element);
					await element?.flow_submit?.();
				}
				return;
			},
			handleDialog_sure() {
				this.$refs.dialogForm.validate(async validate => {
					if (!validate) return;
					await this.submit();
					switch (this.dialog.flag) {
						case '2':
							this.handle_unpass(this.dialog.flag);
							break;
						case '1':
						case '3':
						case '4':
						case '8':
							this.handle_redirct(this.dialog.flag);
							break;
						default:
							break;
					}
				});
			},
			async handle_unpass(val) {
				let result = true;
				for (let index = 0; index < this.components.length; index++) {
					const element = this.components[index];
					let pass;
					if (element?.valid) {
						pass = await element?.valid?.();
					} else {
						pass = true;
					}
					result = result && pass;
				}
				if (!result) {
					this.$message({
						type: 'warn',
						message: '请先完善信息',
					});
					this.scrollToError();
					return;
				}
				const loading = this.$loading({
					lock: true,
					text: 'loading...',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)',
				});
				this.dialog.loading = true;

				let infoData = JSON.stringify(this.infoData);
				let customFormData = JSON.stringify(this.formData);
				let params = Object.assign(
					{
						flag: val,
						message: this.suggest?.message ?? '',
						processInstanceId: this.processId,
						groupId: '1',
						userId: this.userId,
						formData: infoData,
						customFormData: customFormData,
					},
					this.dialog.params,
				);
				// console.log(params);
				// return;
				apis?.FlowAudit(params)
					.then(res => {
						if (res.code == 200) {
							loading.close();
							this.dialog.show = false;
							this.$message.success('加签成功');
							const obj = this.$route;
							this.$tab.closeOpenPage(obj);
							this.$router.push({
								name: 'Approve',
								// path: "/workflow/examine/flowable/examine/list",
							});
						}
					})
					.finally(() => {
						this.dialog.loading = true;
						loading.close();
					});
			},
			async handle_redirct(val) {
				let result = true;
				for (let index = 0; index < this.components.length; index++) {
					const element = this.components[index];
					let pass;
					if (element?.valid) {
						pass = await element?.valid?.();
					} else {
						pass = true;
					}
					result = result && pass;
				}
                // 转办 和 驳回不需要校验
				if (val == '4' || val == '8') {
					if (!result) {
						this.$message({
							type: 'warn',
							message: '请先完善信息',
						});
						this.scrollToError();
						return;
					}
				}
                // if(val !=="3"){
                //     if (!result) {
                //     this.$message({
                //         type: "warn",
                //         message: "请先完善信息",
                //     });
                //     return;
                //     }
                // }


				const loading = this.$loading({
					lock: true,
					text: 'loading...',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)',
				});
				this.dialog.loading = true;
				let infoData = JSON.stringify(this.infoData);
				let customFormData = JSON.stringify(this.formData);
				let word = '';
				let item = this.dicts.apply_sett.find(
					item => item.value == val,
				);
				if (item) {
					word = item.label;
				}
				if (val == '3') {
					word = '驳回';
				}
				let params = Object.assign(
					{
						flag: val,
						message: this.suggest.message,
						processInstanceId: this.processId,
						groupId: '1',
						userId: this.userId,
						formData: infoData,
						customFormData: customFormData,
					},
					this.dialog.params,
				);
				// console.log(params);
				// return;
				apis?.FlowAudit(params)
					.then(res => {
						if (res.code == 200) {
							loading.close();
							this.dialog.show = false;
							this.$message.success(`${word}成功`);
							const obj = this.$route;
							this.$tab.closeOpenPage(obj);
							this.$router.push({
								name: 'Approve',
								// path: "/workflow/examine/flowable/examine/list",
							});
						}
					})
					.finally(() => {
						loading.close();
						loading.close();
					});
			},
			dialog_closed() {
				this.$refs.dialogForm.resetFields();
			},
		},
	};
</script>

<style lang="scss" scoped>
	.container_right {
		width: 350px;
		// padding: 20px;
		// background-color: #fff;
		// padding-top: 20px;
		box-sizing: border-box;
		border-radius: 10px;
		display: flex;
		flex-direction: column;
		gap: 15px 0;
		height: fit-content;
		position: sticky;
		top: 20px;

		.chunk {
			display: flex;
			flex-direction: column;
			gap: 15px 0;

			.title {
				font-weight: 600;
				font-size: 16px;
				color: #333;
			}

			.content {
				::v-deep .el-timeline {
					padding-left: 15px;
				}
			}

			.handleBox {
				display: flex;
				justify-content: space-between;

				::v-deep .el-button + .el-button {
					margin: 0;
				}
			}
		}
	}

	.timeLine_time {
		color: #8c8c8c;
		margin-top: 3px;
	}

	.dialog_content {
		display: flex;
		justify-content: center;
	}

	.status {
		.name {
			font-size: 14px;
			font-family: PingFangSC, PingFang SC;
			font-weight: 500;
			color: #333333;
			line-height: 20px;
		}

		.comp {
			font-size: 14px;
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
			color: #666666;
			line-height: 20px;
		}

		.time {
			font-size: 14px;
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
			color: #999999;
			line-height: 20px;
		}
	}

	.timeLineItem {
		box-sizing: border-box;
		padding: 15px;
		background: #f9fbfe;
		border-radius: 4px;
		font-size: 14px;
		font-family: PingFangSC, PingFang SC;
		font-weight: 400;
		color: rgba(0, 0, 0, 0.85);
		line-height: 20px;
	}

	.willAudit {
		font-size: 14px;
		font-family: PingFangSC, PingFang SC;
		font-weight: 400;
		color: #71767b;
		line-height: 22px;
	}

	.pass {
		font-size: 14px;
		font-family: PingFangSC, PingFang SC;
		font-weight: 400;
		color: #52c41a;
		line-height: 20px;
	}

	.unpass {
		font-size: 14px;
		font-family: PingFangSC, PingFang SC;
		font-weight: 400;
		color: #f5222d;
		line-height: 20px;
	}

	// ::v-deep .el-timeline-item__tail {
	//     border-color: #1890ff;
	// }
</style>
